package oktx.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.PriorityOrdered;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
 * Created by huangdachao on 2018/5/31 17:47.
 */
public class TransactionBeanPostProcessor implements BeanPostProcessor, PriorityOrdered, BeanFactoryAware {
    private BeanFactory beanFactory;

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 1. replace TransactionInterceptor
        if (bean instanceof TransactionInterceptor) {
            TransactionInterceptor interceptor = (TransactionInterceptor) bean;
            return new SpringTransactionInterceptor(beanFactory, interceptor.getTransactionAttributeSource());
        }
        return bean;
    }
}
